package com.cola.dao;

import com.cola.entity.module.Module;
import com.cola.utils.DBControl;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.List;
import java.util.Map;
/**
 * Created by Max on 2017/8/17.
 * 用户Dao
 */
public class UserDao extends BaseDao{
    private static volatile UserDao instance = null;

    public static UserDao getInstance() {
        if (instance == null) {
            synchronized (UserDao.class) {
                if (instance == null) {
                    instance = new UserDao();
                }
            }
        }
        return instance;
    }

    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);

    /**
     * 根据用户名以及密码获取用户信息
     * @param username
     * @param password
     * @return
     */
    public Map<String,Object> getUserInfo(String username,String password){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            String sql = "select a.*,b.role_name from system_user a INNER JOIN system_role b on a.role_id = b.role_id where system_user_name =? and system_user_password =?";
            return getQueryRunner().query(conn,sql,new MapHandler(),username,password);
        }catch (Exception e){
            logger.error("登录获取用户信息异常！");
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }

    /**
     * 根据角色id获取模块列表
     * @param roleId
     * @return
     */
    public List<Module> getUserModuleList(Integer roleId){
        Connection conn = null;
        try{
            conn = DBControl.getConnection();
            String sql = "select b.* from system_module_relation a INNER JOIN system_module b on a.module_id = b.module_id \n" +
                    " where a.role_id = ? ORDER BY module_order";
            return getQueryRunner().query(conn,sql, new BeanListHandler<Module>(Module.class),roleId);
        }catch (Exception e){
            logger.error("根据角色id获取模块列表异常",e);
        }finally {
            DbUtils.closeQuietly(conn);
        }
        return null;
    }


    public static void main(String[] args) {
        System.out.println(UserDao.getInstance().getUserModuleList(1));
    }


}
